import { phoneEncryption } from "../../../utils/util";
import Toast from "tdesign-miniprogram/toast/index";

const app = getApp();

Page({
  data: {
    personInfo: app.globalData.userInfo || {},
    showUnbindConfirm: false,
    pickerOptions: [
      {
        name: "男",
        code: "1",
      },
      {
        name: "女",
        code: "2",
      },
    ],
    typeVisible: false,
    genderMap: ["", "男", "女"],
  },
  onLoad() {
    this.init();
  },
  onShow() {
    this.init();
  },
  init() {
    this.fetchData();
  },
  fetchData() {
    this.setData({
      personInfo: app.globalData.userInfo,
    });
  },
  onClickCell({ currentTarget }) {
    const { dataset } = currentTarget;
    const { nickName } = this.data.personInfo;

    switch (dataset.type) {
      case "gender":
        this.setData({
          typeVisible: true,
        });
        break;
      case "name":
        wx.navigateTo({
          url: `/pages/user/name-edit/index?name=${nickName}`,
        });
        break;
      case "avatarUrl":
        this.modifyAvatar();
        break;
      default: {
        break;
      }
    }
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {
    const { value } = e.detail;
    this.setData(
      {
        typeVisible: false,
        "personInfo.gender": value,
      },
      () => {
        Toast({
          context: this,
          selector: "#t-toast",
          message: "设置成功",
          theme: "success",
        });
      }
    );
  },
  openUnbindConfirm() {
    console.log("退出登录");
  },
  modifyAvatar() {
    const that = this;
    wx.chooseImage({
      count: 1,
      success: (res) => {
        const filePath = res.tempFilePaths[0];
        const cloudPath = `avatars/${Date.now()}-${Math.floor(
          Math.random() * 1000
        )}.png`;
        that.uploadFile(cloudPath, filePath);
      },
      fail: console.error,
    });
  },
  uploadFile(cloudPath, filePath) {
    wx.showLoading({
      title: "上传中",
    });
    const that = this;
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: (res) => {
        const fileID = res.fileID;
        that.getTempFileURL(fileID);
      },
      fail: console.error,
    });
  },
  getTempFileURL(fileID) {
    const that = this;
    wx.cloud.getTempFileURL({
      fileList: [fileID],
      success: (res) => {
        // 更新用户信息
        const tempFileURL = res.fileList[0].tempFileURL;
        that.updateUserInfo(tempFileURL);
      },
      fail: console.error,
    });
  },
  updateUserInfo(tempFileURL) {
    const that = this;
    wx.cloud.callFunction({
      name: "updateUserInfo",
      data: {
        avatarUrl: tempFileURL,
      },
      success: (res) => {
        const userInfo = res.result;
        console.log("userInfo: ", userInfo);
        // 更新全局数据和本地缓存
        app.globalData.userInfo = userInfo;
        wx.setStorageSync("userInfo", userInfo);

        // 使用 setData 更新页面数据，触发视图更新
        that.setData({
          personInfo: { ...userInfo },
        }, () => {
          wx.hideLoading();
          console.log('更新用户信息成功', that.data.personInfo);
          Toast({
            context: this,
            selector: '#t-toast',
            message: '头像更新成功',
            theme: 'success',
          });
        });
      },
      fail: console.error,
    });
  },
});
